﻿using System.Security.Cryptography;
using System.Text;

namespace GMS.NET.Encrypt
{
    public class ShortId
    {
        /// <summary>
        /// 默认生成8位不包含特殊字符的字符串
        /// </summary>
        /// <param name="shortIdConfig"></param>
        /// <returns></returns>
        public static string Create(ShortIdConfig shortIdConfig)
        {
                string chars = shortIdConfig.OptChars!;
                byte[] randomBytes = new byte[shortIdConfig.Length];
                using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
                {
                    rng.GetBytes(randomBytes);
                }
                StringBuilder sb = new StringBuilder(shortIdConfig.Length);
                foreach (byte b in randomBytes)
                {
                    sb.Append(chars[b % chars.Length]);
                }
                return sb.ToString();
        }
    }
    public class ShortIdConfig
    {
        public int Length { get; set; } = 8;
        /// <summary>
        /// 可选字符ShortIdType=String时可用
        /// </summary>
        public string? OptChars { get; set; } = "0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ";
    }
}
